package pyip.lib.javalearn.pattern;

/**
 * 计算某年某月的天数<br>
 * 表驱动是一种编程模式, 方法getDays是表驱动方式, getDays2是ifelse的方式<br>
 * <br>
 * 表驱动法查询数据的方式
 * 1) 直接访问(Direct Access)
 * 2) 索引访问(Index Access）
 * 3) 阶梯访问(Stair-Step Access)
 * 有时需要进行变址查询
 * @author yepeng
 * @date 2015年8月25日
 */
public class TableDriven {
    public int getDays(int year, int month) {

        int[] daysPerMonth = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        int[] daysPerMonthLeapYear = new int[] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

        int days = 0;
        int index = month - 1;

        if (isLeapYear(year)) {
            days = daysPerMonthLeapYear[index];
        } else {
            days = daysPerMonth[index];
        }

        return days;
    }

    public int getDays2(int year, int month) {
        int days = 0;

        switch (month) {
        case 1:
            days = 31;
            break;
        case 2:
            if (isLeapYear(year)) {
                days = 29;
            } else {
                days = 28;
            }
            break;
        case 3:
            days = 31;
            break;
        case 4:
            days = 30;

            // ......

        case 11:
            days = 30;
            break;
        case 12:
            days = 31;
            break;
        default:
            break;
        }

        return days;
    }

    boolean isLeapYear(int i) {
        return true;
    }
}